<template>
  <div>
    <!-- 返回按钮 -->
    <el-button
        v-if="currentLevel !== 'country'"
        type="primary"
        size="medium"
        @click="Back()"
        icon="el-icon-back"
        round
        plain
    >
      返回中国地图
    </el-button>
      <el-button
      v-if="currentLevel === 'country'"
      type="primary"
      size="medium"
      @click="navigateBack"
      icon="el-icon-back"
      round
      plain
  >
    返回首页
  </el-button>
    <div id="main" style="width: 100%; height: 90vh;"></div>

    <!-- 弹窗部分 -->
    <el-dialog
        :visible.sync="dialogVisible"
        :title="dialogTitle"
        width="50%"
        :close-on-click-modal="false"
        top="10px"
    >
      <div>
        <!-- 组别选择器 -->
        <el-form :inline="true">
          <el-form-item label="选择分组">
            <el-select v-model="currentGroup" placeholder="请选择组别">
              <el-option
                  v-for="group in foodGroups"
                  :key="group.name"
                  :label="group.name"
                  :value="group.name"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
                <!-- 搜索框 -->
                <el-input
                v-model="searchQuery"
                placeholder="搜索食物"
                clearable
                style="width: 100%; margin-bottom: 20px;"
              />
        <!-- 当前分组的食物标签 -->
        <div class="food-list">
          <h4>
            当前组别：{{ currentGroup }}
          </h4>
          <el-tag
            v-for="(food, index) in filteredFoods"
            :key="index"
            closable
            @close="removeFood(food)"
            style="margin: 5px;"
          >
            {{ food }}
          </el-tag>
        </div>
        <!-- 美食表格 -->
        <div class="scrollable-table">
          <el-table :data="snackData" style="width: 100%;">
            <el-table-column prop="name" label="美食名称"></el-table-column>
            <el-table-column prop="description" label="介绍"></el-table-column>
            <el-table-column label="操作" width="100">
              <template #default="scope">
                <el-button
                    v-if="isFoodInCurrentGroup(scope.row.name)"
                    type="danger"
                    size="mini"
                    @click="removeFood(scope.row.name)"
                >
                  删除
                </el-button>
                <el-button
                    v-else
                    type="primary"
                    size="mini"
                    @click="addSnackToGroup(scope.row.name)"
                >
                  添加
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <!-- 下探按钮，仅在当前是国家级时显示 -->
      <div v-if="currentLevel === 'country'" style="margin-top: 20px;">
        <el-button type="primary" @click="exploreCity(selectedData.name)">下探到市级地图</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import * as chinaJson from "../ChinaSnackMap/map/中华人民共和国.json";
import { mapGetters,mapMutations } from "vuex";
import {allCitySnacks,provinceCityMap} from '@/assets/foodData/ChinaFoodData.js'

export default {
  data() {
    return {
      currentLevel: "country", // 当前地图层级: country, province
      option: {},
      jsonData: {},
      data: [],
      myChart: null,
      dialogVisible: false,
      dialogTitle: "",
      selectedData:{}, //选中相关的数据
      snackData: [], // 美食数据列表
      currentGroup: "", // 当前选中的组别
      allCitySnacks,
      provinceCityMap,
      searchQuery:''
    };
  },
  computed: {
    ...mapGetters(["foodGroups","selectedGroup", "selectedGroupFoods","getFoodBySelectedGroup"]),
    currentGroupFoods() {
      const group = this.foodGroups.find((g) => g.name === this.currentGroup);
      return group ? group.foods : [];
    },
    filteredFoods() {
      if (!this.searchQuery) return this.currentGroupFoods;
      return this.currentGroupFoods.filter((food) =>
        food.toLowerCase().includes(this.searchQuery.toLowerCase())
      );
    },
  },
  watch:{
    currentGroup(newValue){
      this.updateSelectedGroup(newValue)
    }
  },
  methods: {
    ...mapMutations(["deleteFoodFromGroup","updateSelectedGroup"]),
    navigateBack() {
      this.$router.push("/");
    },
    // 初始化地图
    getChinData(name, jsons) {
      this.$echarts.registerMap(name, jsons);
      let center=[];
      if(this.currentLevel==="country"){
        center=[120.384606, 30.312443]
      }else{
        const {features} = chinaJson
        center=features[this.selectedData.dataIndex].properties.centroid
      }
      const option = {
        title: { text: name, left: "left", textStyle: { color: "#fff" } },
        tooltip: {},
        series: [
          {
            name: name,
            type: "map",
            map: name,
            roam: true,
            center, // 该加载数据的的经纬度中心点
            zoom: 1.3, // 初始缩放级别，按需调整
            label: {
              normal: { show: true, color: "rgb(0,0,0)" },
              emphasis: { show: true, color: "#fff" }
            },
            itemStyle: {
              normal: { areaColor: "#bfe9ff", borderColor: "#000" },
              emphasis: { areaColor: "#e52d27" }
            }
          }
        ]
      };
      this.myChart.setOption(option);
      this.myChart.off("click");
      this.myChart.on("click", this.onRegionClick);
    },
    isFoodInCurrentGroup(foodName) {
      const group = this.foodGroups.find((g) => g.name === this.currentGroup);
      return group ? group.foods.includes(foodName) : false;
    },
    // 区域点击事件
    onRegionClick(params) {
      this.selectedData=params
      // 动态合并省下所有市的美食数据
      if (this.provinceCityMap[params.name]) {
        this.snackData = this.provinceCityMap[params.name].flatMap(
            city => this.allCitySnacks[city] || []
        );
      } else {
        // 直接展示市级美食
        this.snackData = this.allCitySnacks[params.name] || [];
      }
      this.dialogTitle = `${params.name} 美食展示`;
      this.dialogVisible = true;
    },

    // 添加美食到组别
    addSnackToGroup(snackName) {
      if (!this.currentGroup) {
        this.$message.warning("请先选择一个组别！");
        return;
      }
      if (this.isFoodInCurrentGroup(snackName)) {
        this.$message.warning("该小吃已存在于当前分组！");
        return;
      }

      this.$store.commit("addFoodToGroup", {
        groupName: this.currentGroup,
        food: snackName
      });
      this.$message.success(`成功将 ${snackName} 添加到分组 ${this.currentGroup}！`);
    },
    removeFood(foodName) {
      this.deleteFoodFromGroup({
        groupName: this.currentGroup,
        food: foodName
      });
      this.$message.success(`已从分组 ${this.currentGroup} 删除 ${foodName}！`);
    },
    // 下探到市级地图
    async exploreCity(province) {
      const jsonModule = () => import(`@/views/more/ChinaSnackMap/map/${province}.json`);
      this.dialogVisible = false;
      if (this.currentLevel === "country") {
        this.currentLevel = "province";
      }
      try {
        const jsonData = await jsonModule();
        this.getChinData(province, jsonData.default);
      } catch (error) {
        this.currentLevel = "country"
        this.$message.error(`加载 ${province}.json 文件失败`)
      }
    },

    // 返回中国地图
    Back() {
      this.currentLevel = "country";
      this.getChinData("中国", chinaJson);
    },
  },
  mounted() {
    this.myChart = this.$echarts.init(document.getElementById("main"));
    this.currentGroup=this.selectedGroup;
    this.getChinData("中国", chinaJson);
    window.addEventListener("resize", () => {
      this.myChart.resize(); // 使地图根据容器大小重新渲染
    });
  }
};
</script>

<style>
#main {
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
}

/* 限制美食表格的高度，添加滚动 */
.scrollable-table {
  max-height: 300px; /* 设置表格的最大高度 */
  overflow-y: auto; /* 添加垂直滚动 */
  border: 1px solid #ebeef5;
  border-radius: 4px
}
</style>
